package com.ext.aic.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.ext.aic.AICApplication;
import com.ext.aic.R;
import com.ext.aic.apis.chat.AgentReplyRequest;
import com.ext.aic.beans.CustomMedia;
import com.ext.aic.beans.box.NotificationMessage;
import com.ext.aic.beans.params.AgentReplyParams;
import com.ext.aic.beans.response.AgentReplyResponse;
import com.ext.aic.box.AccessibilityObserver;
import com.ext.aic.config.BoxConfig;
import com.ext.aic.constants.EBusConstants;
import com.ext.aic.constants.PermissionConstants;
import com.ext.aic.databinding.MainBinding;
import com.ext.aic.handler.ActivityResultHandler;
import com.ext.aic.utils.BoxUtils;
import com.ext.aic.utils.MainPageNavigationUtils;
import com.ext.aic.utils.PermissionUtils;
import com.ext.aic.utils.PictureUtils;
import com.ext.aic.utils.ToastyUtils;
import com.ext.aic.utils.UserUtils;
import com.ext.aic.utils.XPopupUtils;
import com.eyinfo.android_pure_utils.HandlerManager;
import com.eyinfo.android_pure_utils.ebus.EBus;
import com.eyinfo.android_pure_utils.ebus.SubscribeEBus;
import com.eyinfo.android_pure_utils.events.RunnableParamsN;
import com.lxj.xpopup.impl.ConfirmPopupView;

import java.util.List;

public class MainActivity extends BaseActivity {

    private MainBinding binding;
    private AccessibilityObserver accessibilityObserver = new AccessibilityObserver();
    private ConfirmPopupView unauthorizedDialog;
    private static final int TIME_INTERVAL = 2000;
    private long backPressedTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //layout绑定
        View view = View.inflate(this, R.layout.main, null);
        binding = MainBinding.bind(view);
        setContentView(binding.getRoot());
        //底部导航配置
        MainPageNavigationUtils.getInstance().init(this, binding);
        //无障碍服务监听配置
        accessibilityObserver.setup(this);
        //注册EBus服务
        EBus.getInstance().registered(this);
        activityResultHandler.onCreate(this);
        //延迟处理项
        HandlerManager.getInstance().postDelayed(new RunnableParamsN<Object>() {
            @Override
            public void run(Object... objects) {
                EBus.getInstance().post(EBusConstants.finishSplash);
                authorizationHandler.startAuthorizationTimingDetection();
            }
        }, 100);
        //初始化配置项
        BoxConfig.getInstance().config(this, this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        activityResultHandler.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        activityResultHandler.onPause();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        activityResultHandler.onActivityResult(requestCode, resultCode, data);
    }

    private ActivityResultHandler activityResultHandler = new ActivityResultHandler() {

        @Override
        protected void onFinallyResult(Bundle bundle) {
            BoxUtils.getInstance().onAutoReplyActivityResult(MainActivity.this, bundle);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        accessibilityObserver.destroy();
    }

    @SuppressLint("MissingSuperCall")
    @Override
    public void onBackPressed() {
        if (backPressedTime + TIME_INTERVAL > System.currentTimeMillis()) {
            moveTaskToBack(true);
        } else {
            backPressedTime = System.currentTimeMillis();
        }
    }

    @SubscribeEBus(receiveKey = EBusConstants.enableAutoReplyFeature)
    public void onEnableAutoReplyFeature(boolean isMergeDetectionNotify) {
        BoxUtils.getInstance().enableAutoReplyFeature(this, isMergeDetectionNotify, () ->
                BoxUtils.getInstance().enableAutoReplySuccess(this));
    }

    @SubscribeEBus(receiveKey = EBusConstants.startAccessibilitySettings)
    public void onStartAccessibilitySettings(String autoReplyTag) {
        Intent intent = PermissionUtils.getInstance().getAccessibilitySettingsIntent(autoReplyTag);
        activityResultHandler.startActivityForResult(this, intent, PermissionConstants.REQUEST_CODE_ACCESSIBILITY);
    }

    @SubscribeEBus(receiveKey = EBusConstants.startRestrictedSetting)
    public void onStartRestrictedSetting(String autoReplyTag) {
        Intent intent = PermissionUtils.getInstance().getRestrictedSettingIntent(autoReplyTag);
        activityResultHandler.startActivityForResult(this, intent, PermissionConstants.REQUEST_CODE_BACKGROUND_RESTRICTED);
    }

    @SubscribeEBus(receiveKey = EBusConstants.startNotificationSettings)
    public void onStartNotificationSettings(String autoReplyTag) {
        Intent intent = PermissionUtils.getInstance().getNotificationSettings(autoReplyTag);
        activityResultHandler.startActivityForResult(this, intent, PermissionConstants.REQUEST_CODE_NOTIFICATION);
    }

    @SubscribeEBus(receiveKey = EBusConstants.unauthorized)
    public void onApiUnauthorized() {
        UserUtils.getInstance().clear();
        authorizationHandler.silentAuthorization(this, this, null);
    }

    @SubscribeEBus(receiveKey = EBusConstants.switchMainTab)
    public void onSwitchMainTabEvent(int index) {
        MainPageNavigationUtils.getInstance().switchTab(index);
    }

    @SubscribeEBus(receiveKey = EBusConstants.previewImage)
    public void onPreviewImageEvent(int position, List<CustomMedia> images) {
        PictureUtils.getInstance().preview(this, position, images);
    }

    @SubscribeEBus(receiveKey = {EBusConstants.getAiChatData})
    public void onGetAIChatDataEvent(NotificationMessage message) {
        AgentReplyParams replyParams = new AgentReplyParams();
        replyParams.setUserId(UserUtils.getInstance().getUserId());
        replyParams.setSessionId(message.getSessionId());
        replyParams.setMessage(message.getMessage());
        replyParams.setUsername(message.getUser());
        agentReplyRequest.request(this, this, replyParams);
    }

    private AgentReplyRequest agentReplyRequest = new AgentReplyRequest() {
        @Override
        protected void onAgentReplySuccess(AgentReplyParams params, AgentReplyResponse response) {
            EBus.getInstance().post(EBusConstants.getAiChatDataSuccess, params, response);
        }

        @Override
        protected void onAgentReplyFail() {
            EBus.getInstance().post(EBusConstants.getAiChatDataFail);
        }
    };

    @SubscribeEBus(receiveKey = EBusConstants.interruptedAccessibilityServer)
    public void onInterruptedAccessibilityServerEvent() {
        Activity currentActivity = AICApplication.getInstance().getCurrentActivity();

        String title = getString(R.string.warm_reminder);
        String content = getString(R.string.interrupted_accessibility_server_tip);
        ToastyUtils.getInstance().show(content);
        XPopupUtils.getInstance().showConfirmDialog(currentActivity, title, content, true, () -> {
            System.exit(0);
        });
    }
}
